package org.unigram.oluolu;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapred.OutputLogFilter;

import junit.framework.TestCase;

/**
 *
 * @author takahiko03
 *
 */
public class CheckOutput {
    
    /**
     *
     */
    private CheckOutput() {
        // for safe
    }

    /**
     *
     * @param conf
     * @param output
     * @param expectedPath
     * @throws IOException
     */
    public static void check(Configuration conf,
            final Path output, final Path expectedPath)
    throws IOException {

        FileSystem fs = FileSystem.getLocal(conf);

        Path[] outputFiles = FileUtil.stat2Paths(
            fs.listStatus(output, new OutputLogFilter()));

        if (outputFiles != null) {
            TestCase.assertEquals(outputFiles.length, 1);
        } else {
            TestCase.fail();
        }

        BufferedReader actual   = asBufferedReader(
                fs.open(outputFiles[0]));
        BufferedReader expected = asBufferedReader(
                fs.open(expectedPath));

        String expectedLine;
        while ((expectedLine = expected.readLine()) != null) {
            TestCase.assertEquals(actual.readLine().toString(),
                    expectedLine);
        }
        actual.close();
        expected.close();
    }

    /**
     *
     * @param in
     * @return
     * @throws IOException
     */
    private static BufferedReader asBufferedReader(final InputStream in)
    throws IOException {
        return new BufferedReader(new InputStreamReader(in));
    }

}
